package com.qpl.depression.cms.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qpl.depression.cms.common.ServerResponse;
import com.qpl.depression.cms.entity.Book;
import com.qpl.depression.cms.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class BookController {
    @Autowired
    private BookService bookService;

    /**
     * 跳转到书籍管理页面
     *
     * @return
     */
    @GetMapping("book/page")
    public String bookPage() {
        return "book";
    }

    /**
     * 根据书籍名称 模糊查询书籍信息
     *
     * @param name 名称
     * @return
     */
    @GetMapping("book/data")
    @ResponseBody
    public ServerResponse bookData(String name) {
        List<Book> list = bookService.list(Wrappers.<Book>lambdaQuery().like(StringUtils.isNotBlank(name), Book::getName, name));
        return ServerResponse.createBySuccess("success", list);
    }

    /**
     * 编辑书籍信息
     *
     * @return
     */
    @GetMapping("book/edit")
    public String editPage(Long id, ModelMap map) {
        Book book = bookService.getById(id);
        map.addAttribute("book", book);
        return "bookEditPage";
    }

    /**
     * 编辑书籍信息
     *
     * @return
     */
    @GetMapping("book/add")
    public String bookAdd() {
        return "bookAddPage";
    }

    /**
     * 编辑书籍
     *
     * @return
     */
    @PostMapping("add")
    @ResponseBody
    public ServerResponse add(Book book) {
        return bookService.saveOrUpdate(book) ? ServerResponse.createBySuccessMessage("成功") : ServerResponse.createByErrorMessage("失败");
    }

    /**
     * 删除书籍信息
     *
     * @return
     */
    @GetMapping("delete")
    @ResponseBody
    public ServerResponse delete(Long id) {
        return bookService.removeById(id) ? ServerResponse.createBySuccessMessage("成功") : ServerResponse.createByErrorMessage("失败");
    }

}
